package com.liugh.service.zhongche.Imp;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.liugh.entity.User;
import com.liugh.entity.standard.StandardDownload;
import com.liugh.entity.standard.StandardItem;
import com.liugh.mapper.StandardDownloadMapper;
import com.liugh.mapper.zhongche.StandardItemMapper;
import com.liugh.model.DownloadModel;
import com.liugh.service.IUserService;
import com.liugh.service.zhongche.ISearchService;
import com.liugh.service.zhongche.IStandardDownloadService;
import com.liugh.util.CommonUtil;
import com.liugh.util.FileUpload;
import com.liugh.util.LiughFileUtil;
import com.liugh.util.PDFDownloadWorkUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**标准申请下载 .
 * Created by Fatao on 2018/11/2 .
 */
@Service
public class StandardDownloadServiceImpl implements IStandardDownloadService {

    private static org.slf4j.Logger Logger = LoggerFactory.getLogger(StandardDownloadServiceImpl.class);

    //加水印后文件暂存的位置
    private static String markdownpath;

    @Value("${markdownpath}")
    public void setMarkdownpath(String markdownpath) {
        StandardDownloadServiceImpl.markdownpath = markdownpath;
    }


    @Autowired
    private StandardDownloadMapper standardDownloadMapper;

    @Autowired
    private StandardItemMapper itemMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private ISearchService searchService;


    /**
     * 新增一个申请 .
     * @param standardDownload .
     * @return .
     */
    public StandardDownload addStandDownload(StandardDownload standardDownload,User user) {
        StandardItem item = itemMapper.selectById(standardDownload.getStandardItemId());
        standardDownload.setStandardItemName(item.getStandName());
        standardDownload.setApplyTime(new Date());
        standardDownload.setStandardItemNo(item.getStandNo());
        standardDownload.setApplyUserNo(user.getUserNo());
        return CommonUtil.isDBOpSuccess(standardDownloadMapper.insertAllColumn(standardDownload)) ? standardDownload : null;

    }

    /**
     * 删除一条申请 .
     * @param id .
     * @return .
     */
    public boolean delStandDownload(int id) {
        return CommonUtil.isDBOpSuccess(standardDownloadMapper.deleteById(id));
    }


    /**
     * 根据id获取一条记录 .
     * @param id .
     * @return .
     */
    public StandardDownload getStandardDownById(int id) {
        return standardDownloadMapper.selectById(id);
    }


    /**
     * 分页获取所有申请人的申请下载条目 .
     * @param page .
     * @return .
     */
    public Page<StandardDownload> getAllStandardDownloadByUser(Page<StandardDownload> page,User user) {

        List<StandardDownload> standardDownloadList = standardDownloadMapper.selectPage(page, new EntityWrapper<StandardDownload>().eq("apply_user_no",user.getUserNo()).orderBy("apply_time",false));

        for (StandardDownload standardDownload : standardDownloadList) {
            standardDownload.setApplyUserName(userService.getUserByUserNo(standardDownload.getApplyUserNo()).getUsername());
            if (standardDownload.getApproveNo() != null) {
                standardDownload.setApproveUserName(userService.getUserByUserNo(standardDownload.getApproveNo()).getUsername());
            }
        }

        page.setRecords(standardDownloadList);
        return page;
    }


    /**
     * 分页获取所有申请下载条目 .
     * @param page .
     * @return .
     */
    public Page<StandardDownload> getAllStandardDownload(Page<StandardDownload> page) {

        List<StandardDownload> standardDownloadList = standardDownloadMapper.selectPage(page, new EntityWrapper<>());

        for (StandardDownload standardDownload : standardDownloadList) {
            standardDownload.setApplyUserName(userService.getUserByUserNo(standardDownload.getApplyUserNo()).getUsername());
            if (standardDownload.getApproveNo() != null) {
                standardDownload.setApproveUserName(userService.getUserByUserNo(standardDownload.getApproveNo()).getUsername());
            }
        }
        page.setRecords(standardDownloadList);
        return page;
    }

    /**
     * 拒绝下载
     * @param download
     * @return
     */
    @Override
    public StandardDownload refuseDownloadApply(StandardDownload download) {
        return CommonUtil.isDBOpSuccess(standardDownloadMapper.updateById(download)) ? download : null;
    }

    /**
     * 处理下载文件请求
     * @param download
     * @throws IOException
     */
    @Override
    @Transactional
    public boolean handleDownloadApply(StandardDownload download) throws IOException {
        boolean isSuccess = false;

        PDFDownloadWorkUtil markUtil = new PDFDownloadWorkUtil();
        StandardItem item = itemMapper.selectById(download.getStandardItemId());
        User user = userService.getUserByUserNo(item.getAuthor());

        FileUtil.mkdir(markdownpath);
        //文件暂存路径
        String path = markdownpath + "/" + item.getStandName() + "." + FileUtil.extName(item.getUploadDir());

        //文件上传存储路径
        String storePath;

        File file = new File(path);

        try {
            isSuccess = markUtil.waterMarkUrl(URLUtil.url(item.getUploadDir()), path, user.getUsername());
            if (isSuccess) {
                //将加完水印的图片上传
                storePath = FileUpload.saveFile(LiughFileUtil.fileToMulFile(file));

                //更新DB
                download.setApplyDir(storePath);
                standardDownloadMapper.updateById(download);

                //存储原始文件名
                String filename = searchService.getOriginName(CommonUtil.getFileNameByUrl(item.getUploadDir()));
                searchService.addOriginName(CommonUtil.getFileNameByUrl(storePath), filename);
            }
        } catch (IOException e) {
            Logger.error("添加水印失败");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtil.del(file);
        }
        return isSuccess;
    }

    @Override
    public StandardDownload updateDownload(StandardDownload download) {
        return CommonUtil.isDBOpSuccess(standardDownloadMapper.updateById(download)) ? download : null;
    }


    /**
     * 下载，返回文件链接及原始文件名
     * @param id
     * @return
     */
    @Override
    public DownloadModel download(int id) {
        StandardDownload download = standardDownloadMapper.selectById(id);
        StandardItem item = itemMapper.selectList(new EntityWrapper<StandardItem>().where("id = {0}",download.getStandardItemId())).get(0);

        if (item != null) {
            String originName = searchService.getOriginName(CommonUtil.getFileNameByUrl(item.getUploadDir()));
            String filePath = download.getApplyDir();

            if (!(StrUtil.isEmpty(originName) && StrUtil.isEmpty(filePath))) {
                return new DownloadModel(filePath, originName);
            }
        }
        return null;
    }
}
